import { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Tabs,
  Space,
  Button,
  Form,
  Row,
  Col,
  Input,
  message,
  Select,
  DatePicker,
  Checkbox,
  notification,
  Modal,
  Table,
} from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import {
  PlusOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  CheckOutlined,
  PrinterOutlined,
  SaveOutlined,
  ExportOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import ShipDtlSo from './components/shipDtlSo';
import request from '@/utils/request';
import moment from 'moment';
import CateComp from '@/components/CategoryComponent';
import { EmpSelect } from '@/components/FormItemSelect';
import TempleteShip from '../PrintTemplete/TempleteShip';
import PrintModal from '@/components/PrintModal';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/ShipHead/';
const apiURLDtl = '/api/services/app/ShipDtl/';
const apiURLCus = '/api/services/app/Customers/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [data, setData] = useState<any>({});
  const [defTab, setDefTab] = useState('1');
  const [optionCust, setOptionCust] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [selectedSORows, setSelectedSORows] = useState([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const formRef = useRef<any>();
  const [record,setRecord] = useState<any>();
  let shipDtlPo: any = ShipDtlSo;
  const onRef = (ref: any) => {
    shipDtlPo = ref;
  };
  const intl = useIntl();

  useEffect(() => {
    fetchCusts();
  }, []);

  const fetchCusts = () => {
    setLoading(true);
    request(apiURLCus + 'GetAll', {
      method:'GET',
      params: { SkipCount: 0, MaxResultCount: 9999 },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setOptionCust(response.result?.items);
          setLoading(false);
        } 
      }
    });
  };

  const onFinish = (values: any) => {
    save(values.ShipHead);
  };

  const resetForm = () => {
    const data = { packNum: '0', id: '0' };
    formRef.current.resetFields();
    formRef.current.setFieldsValue({ ShipHead: data });
    setData({
      data: { id: '0', shipCmpl: false },
      details: [],
    });
  };

  const save = (model: any) => {
    let act = 'Modify';
    const method = 'POST';
    model.shipDate = model.shipDate?.format('YYYY-MM-DD');
    model.entryDate = model.entryDate?.format('YYYY-MM-DD');
    if (model.id === '0') {
      act = 'New';
      model.id = undefined;
      model.shipStatus = '未结';
    }
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
          const packNum = response.result.data
            ? response.result.data.packNum
            : response.result.packNum;
          getObj(packNum);
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        setLoading(false);
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const getObj = (value: any) => {
    if (!value) {
      return;
    }
    setLoading(true);
    request(apiURL + 'GetByNum', {
      method: 'GET',
      params: { num: value },
    }).then((response) => {
      if (response) {
        if (response.success) {
          const result = response.result;
          const data = result.data;
          if (data) {
            if (data.shipDate) data.shipDate = moment(data.shipDate);
            if (data.entryDate) data.entryDate = moment(data.entryDate);
            formRef.current.setFieldsValue({ ShipHead: data });
            setData(result);
            setVisible(false);
            setLoading(false);
          }
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    if (data.data) {
      confirm({
        title: intl.formatMessage({ id: 'pages.warning' }),
        icon: <ExclamationCircleOutlined />,
        content: intl.formatMessage({ id: 'pages.delete?' }),
        onOk() {
          request(apiURL + 'DelBatch', {
            method: 'POST',
            data: [data.data.id],
          }).then((response) => {
            if (response) {
              if (response.success) {
                resetForm();
              }
            }
          });
        },
      });
    }
  };

  const switchModal = (visible: boolean, record: any = null) => {
    if (record == null) {
      record = {
        packNum: data.data?.packNum,
        custNum: data.data?.custNum,
      };
    }
    setVisible(visible);
    setRecord(record);
  };

  const switchModal2 = (visible: boolean, record: any = null) => {
    if (record == null) {
      record = {
        packNum: data.data?.packNum,
        custNum: data.data?.custNum,
      };
    }
    setVisible3(visible);
    setRecord(record);
  };

  const CustSelChange = (e: any) => {
    const obj = optionCust.filter((o: any) => o.custNum == e)[0];
    const ShipHead: any = {};
    ShipHead.ffCountry = obj.country;
    ShipHead.ffState = obj.state;
    ShipHead.ffCity = obj.city;
    ShipHead.ffAddress1 = obj.contAddress;
    formRef.current.setFieldsValue({ ShipHead });
  };

  const delDtl = () => {
    setLoading(true);
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete?' }),
      onOk() {
        request(apiURLDtl + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys,
        }).then((response) => {
          if (response) {
            if (response.success) {
              const _data = data;
              _data.details = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
              setData(_data);
              setLoading(false);
              setSelectedRowKeys([]);
            }
          }
        });
      },
    });
  };

  const completeDtl = () => {
    const arrs: any = [];
    selectedRows.forEach((item: any) => {
      arrs.push({
        packNum: item.packNum,
        packLine: item.packLine,
      });
    });
    request(apiURLDtl + 'Complete', {
      method: 'POST',
      data: arrs,
    }).then((response) => {
      if (response.success) {
        const result = response.result;
        if (result.success) {
          message.success(intl.formatMessage({ id: 'pages.ship.success' }));
          getObj(arrs[0].packNum);
        } else {
          message.error(result.message);
        }
      }
    });
  };

  const handlePrint = () => {
    setVisible2(true);
  };

  const handlePatchShip = () => {
    const shipHed = data.data;
    let i = data.details?.length + 1;
    selectedSORows.forEach((element: any) => {
      const obj = {
        packNum: shipHed.packNum,
        packLine: i,
        warehouseCode: 'WGJ',
        binNum: '1',
        custNum: shipHed.custNum,
        orderNum: element.OrderNum,
        orderLine: element.OrderLine,
        orderRelNum: element.OrderRelNum,
        ourJobShipQty: element.OurReqQty,
        partNum: element.PartNum,
        partDescription: element.PartDescription,
        unitCost: element.UnitPrice,
        ium: element.IUM,
      };
      handleShip(obj);
      i++;
    });
    getObj(shipHed.packNum);
    setVisible3(false);
  };

  const handleShip = (model: any) => {
    setLoading(true);
    request('/api/services/app/ShipDtl/Create', {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          setLoading(false);
        }
      }
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const columns = [
    {
      title: <FormattedMessage id="pages.packNum" />,
      dataIndex: 'packNum',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.packLine" />,
      dataIndex: 'packLine',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.orderNum" />,
      dataIndex: 'orderNum',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'ourJobShipQty',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.complete" />,
      dataIndex: 'shipCmpl',
      width: 60,
      render: (text: boolean) => <Checkbox checked={text} />,
    },
  ];
  const optionCustItem = optionCust?.map((d: any) => {
    return (
      <Select.Option value={d.custNum} key={d.id}>
        {d.customerName}
      </Select.Option>
    );
  });
  const rowSelection = {
    selectedRowKeys,
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setSelectedRowKeys(_selectedKeys);
      setSelectedRows(selectedRows);
    },
  };
  const rowSelection2 = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setSelectedSORows(selectedRows);
    },
  };
  const disabled = data?.data == undefined || data?.data?.shipCmpl;
  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={<FormattedMessage id="menu.saleorder.shipEntry" />}
          extra={
            <Space>
              <Button key="1" type="default" onClick={resetForm}>
                <span>
                  <FormattedMessage id="pages.reset" />
                </span>
              </Button>
              <Button
                key="2"
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                disabled={disabled}
              >
                <span>
                  <FormattedMessage id="pages.save" />
                </span>
              </Button>
              <Button
                key="4"
                type="primary"
                danger
                icon={<CloseOutlined />}
                onClick={delObj}
                disabled={disabled}
              >
                <span>
                  <FormattedMessage id="pages.delete" />
                </span>
              </Button>
              <Button
                key="5"
                type="primary"
                icon={<SyncOutlined />}
                onClick={() => getObj(data?.data.packNum)}
                disabled={disabled}
              >
                <span>
                  <FormattedMessage id="pages.refresh" />
                </span>
              </Button>
              <Button type="ghost" icon={<PrinterOutlined />} onClick={handlePrint}>
                <span>
                  <FormattedMessage id="pages.print" />
                </span>
              </Button>
              <QuickMenu path="/part/shipEntry" icon="icon-shipped" title="pages.ShipEntry" />
            </Space>
          }
        >
          <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
            <TabPane tab={<FormattedMessage id="pages.summary" />} key="1">
              <Row>
                <Col span={12}>
                  <Form.Item name={['ShipHead', 'id']} hidden={true}>
                    <Input />
                  </Form.Item>
                  <Form.Item name={['ShipHead', 'shipStatus']} hidden={true}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.packNum" />}
                    name={['ShipHead', 'packNum']}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.packNum.required" /> },
                    ]}
                  >
                    <Input
                      style={{ width: 200 }}
                      onBlur={(e: any) => getObj(e.target.value)}
                      disabled
                    />
                  </Form.Item>
                  <Form.Item
                    name={['ShipHead', 'shipDate']}
                    label={<FormattedMessage id="pages.shipDate" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.shipDate.required" /> },
                    ]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <EmpSelect
                    showSearch
                    width={200}
                    name={['ShipHead', 'shipPerson']}
                    label={<FormattedMessage id="pages.shipPerson" />}
                    params={{
                      deptCode: 'WD',
                    }}
                    tooltip={intl.formatMessage({id: 'pages.selectWDEmployee'})}
                  />
                  <CateComp
                    layout="ShipVia"
                    width={200}
                    name={['ShipHead', 'shipViaCode']}
                    label={<FormattedMessage id="pages.shipViaCode" />}
                  />
                  <Form.Item
                    name={['ShipHead', 'custNum']}
                    label={<FormattedMessage id="pages.customer" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.customer.required" /> },
                    ]}
                  >
                    <Select
                      style={{ width: 280 }}
                      placeholder={<FormattedMessage id="pages.select" />}
                      showSearch
                      onChange={CustSelChange}
                      filterOption={(input, option: any) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {optionCustItem}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label={<FormattedMessage id="pages.shipAddress" />}
                    style={{ marginBottom: 0 }}
                    required
                  >
                    <Input.Group compact>
                      <Form.Item
                        name={['ShipHead', 'ffCountry']}
                        rules={[
                          {
                            required: true,
                            message: <FormattedMessage id="pages.ffCountry.required" />,
                          },
                        ]}
                      >
                        <Input placeholder={intl.formatMessage({id:'pages.country'})} />
                      </Form.Item>
                      <Form.Item
                        name={['ShipHead', 'ffState']}
                        rules={[
                          { required: true, message: <FormattedMessage id="pages.ffState.required" /> },
                        ]}
                      >
                        <Input placeholder={intl.formatMessage({id:'pages.state'})} />
                      </Form.Item>
                      <Form.Item
                        name={['ShipHead', 'ffCity']}
                        rules={[
                          { required: true, message: <FormattedMessage id="pages.ffCity.required" /> },
                        ]}
                      >
                        <Input placeholder={intl.formatMessage({id:'pages.city'})} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.ffAddress" />}
                    name={['ShipHead', 'ffAddress1']}
                    rules={[{ required: true }]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['ShipHead', 'shipComment']}
                    label={<FormattedMessage id="pages.shipComment" />}
                  >
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 5 }}>
                    <Input.Group compact>
                      <Form.Item name={['ShipHead', 'shipCmpl']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.complete" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['ShipHead', 'invoiced']} valuePropName="checked">
                        <Checkbox disabled>
                          <FormattedMessage id="pages.invoiced" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.shipDetail" />} key="2">
              <Table
                rowKey="id"
                size="small"
                columns={columns}
                loading={loading}
                dataSource={data.details}
                rowSelection={rowSelection}
                pagination={false}
                footer={() => (
                  <Space>
                    <Button
                      block
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={() => switchModal(true)}
                      disabled={data.data?.id == null}
                    >
                      <span>
                        <FormattedMessage id="pages.newDetail" />
                      </span>
                    </Button>
                    <Button
                      block
                      type="ghost"
                      icon={<ExportOutlined />}
                      onClick={() => switchModal2(true)}
                      disabled={data.data?.id == null}
                    >
                      <span>
                        <FormattedMessage id="pages.shipBatch" />
                      </span>
                    </Button>
                    <Button
                      type="primary"
                      icon={<CheckOutlined />}
                      onClick={completeDtl}
                      disabled={selectedRowKeys.length <= 0}
                    >
                      <span>
                        <FormattedMessage id="pages.shipComplete" />
                      </span>
                    </Button>
                    <Button
                      type="dashed"
                      danger
                      icon={<CloseOutlined />}
                      onClick={delDtl}
                      disabled={selectedRowKeys.length <= 0}
                    >
                      <span>
                        <FormattedMessage id="pages.delete" />
                      </span>
                    </Button>
                  </Space>
                )}
                onRow={(item) => {
                  return {
                    onDoubleClick: () => {
                      switchModal(true, item);
                    },
                  };
                }}
              />
            </TabPane>
          </Tabs>
        </Card>
      </Form>
      <OperpQuery
        sysReportName="ReportShip"
        scroll={{ x: 'max-content', y: '200px' }}
        params={{
          freshNum: 1,
        }}
        callback={(e) => getObj(e.PackNum)}
      />
      <Modal
        title={<FormattedMessage id="pages.shipDetail" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => switchModal(false)}
        footer={false}
        width={680}
      >
        <ShipDtlSo onRef={onRef} data={record} callback={getObj} />
      </Modal>
      <Modal
        title={<FormattedMessage id="pages.shipPatch" />}
        visible={visible3}
        destroyOnClose={true}
        onCancel={() => switchModal2(false)}
        footer={
          <Button
            type="primary"
            onClick={handlePatchShip}
            disabled={selectedSORows.length <= 0}
          >
            <FormattedMessage id="pages.submit" />
          </Button>
        }
        width={880}
        bodyStyle={{ padding: '0px' }}
      >
        <OperpQuery
          sysReportName="SoSearch"
          scroll={{ x: 'max-content', y: '200px' }}
          search={{
            filterType: 'light',
          }}
          rowSelection={rowSelection2}
          params={{
            OpenOrder: 1,
            VoidOrder: 0,
            Approve: 1,
            OpenRelease: 1,
          }}
        />
      </Modal>
      <Modal
        width={1024}
        title={<FormattedMessage id="pages.print" />}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <PrintModal>
          <TempleteShip data={data} configData={props.currentConfig} />
        </PrintModal>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
  currentConfig: user.currentConfig,
}))(ViewPage);
